<template>
  <ul class="xitongYonghu" style="z-index: 1">

    <li class="xitongYonghu-top">

      <ul class="xitong-search" style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">

        <li style="width: 160px">
          <el-button plain @click="dialogFormVisible = true">
            添加
          </el-button>
          <el-button @click="deleteTick">
            勾选删除
          </el-button>
        </li>

        <li style="width: 420px">
          <input style="height: 32.5px;width: 250px;box-sizing: border-box;padding: 5px 10px;border-radius: 5px;border: none" type="text" v-model="searchAll">
          <el-button @click="serchBtn" style="margin-left: 10px">
            🔍搜索
          </el-button>
          <el-button @click="resetSerchbtn">
            重置
          </el-button>
        </li>

      </ul>

      <!--    展示  添加-->
      <el-dialog v-model="dialogFormVisible" title="添加页面" width="500">
        <el-form :model="form2">
          <el-form-item label="id" :label-width="formLabelWidth" required>
            <el-input v-model="form2.id" />
          </el-form-item>
          <el-form-item label="username" :label-width="formLabelWidth" required>
            <el-input v-model="form2.username" />
          </el-form-item>
          <el-form-item label="password" :label-width="formLabelWidth" required>
            <el-input v-model="form2.password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="nickname" :label-width="formLabelWidth" required>
            <el-input v-model="form2.nickname" />
          </el-form-item>
          <el-form-item label="email" :label-width="formLabelWidth" required>
            <el-input v-model="form2.email" autocomplete="off" />
          </el-form-item>
          <el-form-item label="phone" :label-width="formLabelWidth" required>
            <el-input v-model="form2.phone" />
          </el-form-item>
          <el-form-item label="salt" :label-width="formLabelWidth" required>
            <el-input v-model="form2.salt" />
          </el-form-item>
          <el-form-item label="role" :label-width="formLabelWidth" required>
            <el-input v-model="form2.role" autocomplete="off" />
          </el-form-item>
          <el-form-item label="del" :label-width="formLabelWidth" required>
            <el-input v-model="form2.del" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser">
              确认添加
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!--    修改页面 -->
      <el-dialog v-model="xiugaiVisible" title="修改页面" width="500">
        <el-form :model="form2">
          <el-form-item label="id" :label-width="formLabelWidth" required>
            <el-input v-model="form2.id" />
          </el-form-item>
          <el-form-item label="username" :label-width="formLabelWidth" required>
            <el-input v-model="form2.username" />
          </el-form-item>
          <el-form-item label="password" :label-width="formLabelWidth" required>
            <el-input v-model="form2.password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="nickname" :label-width="formLabelWidth" required>
            <el-input v-model="form2.nickname" />
          </el-form-item>
          <el-form-item label="email" :label-width="formLabelWidth" required>
            <el-input v-model="form2.email" autocomplete="off" />
          </el-form-item>
          <el-form-item label="phone" :label-width="formLabelWidth" required>
            <el-input v-model="form2.phone" />
          </el-form-item>
          <el-form-item label="salt" :label-width="formLabelWidth" required>
            <el-input v-model="form2.salt" />
          </el-form-item>
          <el-form-item label="role" :label-width="formLabelWidth" required>
            <el-input v-model="form2.role" autocomplete="off" />
          </el-form-item>
          <el-form-item label="del" :label-width="formLabelWidth" required>
            <el-input v-model="form2.del" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="xiugaiVisible = false">取消</el-button>
            <el-button type="primary" @click="EditUser">
              确认修改
            </el-button>
          </div>
        </template>
      </el-dialog>
    </li>
    <li>
      <el-table v-if="isShow" :data="itemsArr" style="width: 99%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="Id" width="100px" />
        <el-table-column prop="username" label="Username" width="150px" />
        <el-table-column prop="password" label="Password" width="120px" />
        <el-table-column prop="nickname" label="Nickname" width="150px" />
        <el-table-column prop="email" label="Email" width="250px" />
        <el-table-column prop="phone" label="Phone" width="120px"/>
        <el-table-column align="right">
          <template #header>
            <p>用户操作</p>
          </template>
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row.id)">
              修改
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table v-else :data="filteruserArr" style="width: 99%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="Id" width="100px" />
        <el-table-column prop="username" label="Username" width="150px" />
        <el-table-column prop="password" label="Password" width="120px" />
        <el-table-column prop="nickname" label="Nickname" width="150px" />
        <el-table-column prop="email" label="Email" width="250px" />
        <el-table-column prop="phone" label="Phone" width="120px"/>
        <el-table-column align="right">
          <template #header>
            <p>用户操作</p>
          </template>
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row.id)">
              修改
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </li>
    <li>
      <el-pagination v-if="isShow"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[3, 5, 10]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalItems">
      </el-pagination>
      <p v-else></p>
    </li>
  </ul>



</template>

<script setup>

import { ElPagination } from 'element-plus';
import index, {useStore} from "vuex";
import { computed, ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios  from "axios";
const now = new Date();
const search = ref('')
const store = useStore();
const dialogFormVisible = ref(false);
// 来显示搜索框和原数据框的显示和隐藏
let isShow = ref(true);

//搜索关键字
let searchAll = ref("");

//修改页面的初始值  false不显示
const xiugaiVisible = ref(false);
const formLabelWidth = '140px';
//定义数组
const userArr = computed(()=>{
  return store.state.xitongUserArr;
})
// -----------------------------------------

const currentPage = ref(1); // 当前页码 默认是1
const pageSize = ref(5); // 每页显示的条目数  默认是5
const totalItems = computed(()=> userArr.value.length); // 总条目数，userArr已经初始化
// 当前页的条目数据
const itemsArr = computed(()=> userArr.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
))
// -----------------------------------------

let form2 = ref({
  id:"",
  username: "",
  password: "", // 未加密密码
  nickname: "",
  email: "",
  phone: "",
  salt: "",
  role: "", // 管理员
  del: "",
})

//查找功能
const filteruserArr = computed(() =>
    //filter接受一个回调函数作为参数，并返回一个新数组，该数组包含所有使得回调函数返回true的元素
    userArr.value.filter(
        (data) =>
            !searchAll.value ||
            String(data.id).includes(String(searchAll.value)) ||
            data.username.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.password.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.nickname.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.email.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.phone.toLowerCase().includes(searchAll.value.toLowerCase())
    )
)
// 点击搜索
const serchBtn = function () {
  isShow.value = false;
}
//重置
const resetSerchbtn =function () {
  isShow.value = true;
  searchAll.value = "";
}
// =====================================================
// 封装方法
const sendIndexofId = function (id) {
  for (let i = 0; i < userArr.value.length; i++) {
    if (id === userArr.value[i].id) {
      return i;
    }
  }
}
const panduanId = function () {
  //假设不存在
  let idcunzai = false;
  console.log("form2.value.id的值为" + form2.value.id);
  //判断id是否已存在,如果已存在,那么就不添加
  for (let i = 0; i < userArr.value.length; i++) {
    if (form2.value.id == userArr.value[i].id) {
      console.log("userArr.value[" +i+ "].id的值为" + userArr.value[i].id);
      idcunzai = true;
    }
  }
  console.log("idcunzai的值为" + idcunzai);
  return idcunzai;
}
//传入一个对象, 如果有这个对象中至少存在一个空字符串,那么就返回true
const hasEmptyString = function (obj) {
  return Object.values(obj).some(value => value === '');
}

//分页逻辑处理
//==================================================
//点击事件:更改所要显示页面的用户信息数量(条目数), newSize和newPage的值来源于Element UI分页组件内部的状态
const handleSizeChange = (s) => {
  pageSize.value = s;
};
//点击事件:更改所要显示的页面
const handleCurrentChange = (newPage) => {
  console.log("所要显示的页面:"+newPage);
  currentPage.value = newPage;
};

//==================================================

//   ----------------------  点击事件添加----------------------------
const addUser = function () {
  //先判断是否有空输入框
  if (hasEmptyString(form2.value)){
    open3();  //有空字符串   失败
  }else{
    if (panduanId()){  //id已存在
      open4();
    }else{  //id不存在
      store.commit("addObjTouserList", form2);
      dialogFormVisible.value = false;
      open();
    }
  }
}
//===============================

let changePageSendId = 0;
let chushiFrom2Id = 0;
//进入修改页面
const handleEdit = (id) => {
  changePageSendId = id;
  console.log("修改页面所传id为:" + changePageSendId);
  let changeIndex = sendIndexofId(id);  //返回下标,通过下标获取对象
  console.log("修改页面所传index为:" + changeIndex);
  //显示修改页面
  xiugaiVisible.value = true;
  //每次点完就传一个下标,根据下标从vuex中取得对象,取完后进行修改再将此对象进行删除后添加
  form2.value = {
    id: store.state.xitongUserArr[changeIndex].id,
    username: store.state.xitongUserArr[changeIndex].username,
    password: store.state.xitongUserArr[changeIndex].password, // 未加密密码
    nickname: store.state.xitongUserArr[changeIndex].nickname,
    email: store.state.xitongUserArr[changeIndex].email,
    phone: store.state.xitongUserArr[changeIndex].phone,
    salt: store.state.xitongUserArr[changeIndex].salt,
    role: store.state.xitongUserArr[changeIndex].role, // 管理员
    del: store.state.xitongUserArr[changeIndex].del,
  }
  chushiFrom2Id = form2.value.id;//获取form2的初始id
}
//确认修改 按钮事件
const EditUser = function () {
  let changeIndex = sendIndexofId(changePageSendId);  //返回下标,通过下标获取对象
  //先判断是否有空输入框
  if (hasEmptyString(form2.value)){
    open3();  //有空字符串   失败
  }else{
    if (chushiFrom2Id === form2.value.id){ //id值都没有动
      store.commit("modifyObjOfuserList", {index:changeIndex,obj:form2});
      open2(); //修改成功
    }else{  // id值变了
      if (panduanId()){ //id已存在
        open4();
      }else{ //id不存在
        store.commit("modifyObjOfuserList", {index:changeIndex,obj:form2});
        open2();
      }
    }
  }

  //关闭修改页面
  xiugaiVisible.value = false;

}

//删除
const handleDelete = (id) => {
  let changeIndex = sendIndexofId(id);  //id一定存在
  store.commit("deleteObjByindexofuserList", changeIndex)
  open1();
}

// 创建一个方法数组,让一个数去便利其中的id值, 如果没有包含此数,那么就用这个数作为新添加的id
//添加成功
const open = () => {
  ElMessage({
    message: '添加成功.',
    type: 'success',
  })
}
//删除成功
const open1 = () => {
  ElMessage({
    message: '删除成功.',
    type: 'success',
  })
}
//修改成功
const open2 = () => {
  ElMessage({
    message: '修改成功.',
    type: 'success',
  })
}
//有空字符串  失败
const open3 = () => {
  ElMessage.error('输入框中不能为空,请重试');
}
//修改失败
const open4 = () => {
  ElMessage.error('修改失败,输入的id已存在');
}


</script>

<style scoped>
.xitongYonghu{
  width: 99%;
  background-color: #cccccc;
  padding: 15px;
}
.xitongYonghu li{
  width: 100%;
  border-radius: 5px;
}
.xitongYonghu-top {
  background-color: transparent;
  margin-bottom: 10px;
}
.el-pagination{
  margin-top: 10px;
}

</style>